<template>
  <cj-popup v-model="isShow" @closed="closed" class="sec-popup">
    <article class="c-maxw640" :class="direction == 'HOR' ? 'c-ww540' : 'c-ww440'">
      <img class="c-w100" id="honorCertImg" src="" alt="" />
      <div class="c-fs24 c-fc-white c-textAlign-c c-mt16">长按保存图片，分享给好友</div>
      <div class="c-fs24 c-fc-white c-textAlign-c c-mt8" v-if="isGoAchievem == 1">前往<span class="theme-fc" @click.stop="goToAchievem">我的成就</span>查看更多证书</div>
    </article>
  </cj-popup>
</template>

<script>
import { utilJs } from '@/utils/common.js';
import { Json2canvas } from '@/utils/json2image.js';
import { getCustCertJson, getVerCertJson, getHorCertJson } from '@/utils/canvasJson/honorCertJson.js';
const CERT_TYPE = 3;
export default {
  components: {},

  props: {
    isGoAchievem: { //是否显示前往我的证书 目前只有首页证书才有显示
      type: Number,
      default: 0
    }
  },

  data() {
    return {
      isShow: false,
      direction: 'HOR'
    };
  },

  created() {},
  mounted() {
    this.initJson2image();
  },
  beforeDestroy() {
    this.destroyJson2image();
    this.isShow = false;
  },
  methods: {
    public_open(info) {
      this._prodId = info.id;
      this._cardId = info.cardId;
      this._isReceivedStudy = info.isReceivedStudy || 0;
      this.$loading.show({
        text: '证书生成中'
      });
      console.time('totalTime');
      console.time('getCertofocateInfoTime');
      this.__certInfo = null;
      this._canvasWidth = 750;
      this._canvasHeight = 1334;
      this.getCertofocateInfo();
    },
    public_showImg(src, dir) {
      this.isShow = true;
      this.direction = dir;
      let ig = document.getElementById('honorCertImg');
      ig.setAttribute('src', src);
    },
    closed() {
      this.$loading.hide();
    },
    getUploadImgSign() {
      return new Promise(resolve => {
        utilJs.getAliSign(`${global.apiurl}imageSign`, res => {
            this._imageSign = res;
            resolve();
          });
      })
    },
    getCertofocateInfo() {
      console.time('getMethodTime');
       utilJs.getMethod(`${global.apiurl}Certificate/cardShow?id=${this._prodId}&type=${CERT_TYPE}`, res => {
          console.timeEnd('getMethodTime');
          this.direction = res.shapeType == 1 ? 'VER' : 'HOR';
          let bgImgUrl = '';
          let title = '';
          let customizeQrCode = '';
          let redirectTo = '';
          let qrCodeText = '';
          let createdAt = '';
          let headimgurl = res.headimgurl || require('@/assets/defult_head.png');
          let nickname = res.nickname;
          let realName = res.realName;
          let number = res.number && `证书编号：${res.number}`;
          let qrCodeUrl = res.defaultBaseInfo.qrCodeUrl;
          let homeQrcode = res.defaultBaseInfo.homeQrcode;
          let customizeControl = [];
          let enableAvatarShow = '';
          let nameTypeShow = '';
          let longContent = '';
          let enableShowQrCode = '';
          let enableInstitution = '';
          let institutionName = '';
          let enableGrantTime = '';
          let enableNumber = '';
          let enableStamp = '';
          let stampImg = '';

          //自定义证书
          if (res.certificateType == 2 && res.customizeControl) {
            const MAGNIFICATION = 2; //放大倍数
            for (let i = 0; i < res.customizeControl.length; i++) {
              res.customizeControl[i].height = res.customizeControl[i].height * MAGNIFICATION;
              res.customizeControl[i].width = res.customizeControl[i].width * MAGNIFICATION;
              res.customizeControl[i].lineHeight = res.customizeControl[i].lineHeight * MAGNIFICATION;
              res.customizeControl[i].left = res.customizeControl[i].posX * MAGNIFICATION;
              res.customizeControl[i].top = res.customizeControl[i].posY * MAGNIFICATION;
              res.customizeControl[i].fontSize = res.customizeControl[i].size * MAGNIFICATION;
              res.customizeControl[i].letterSpacing = res.customizeControl[i].letterSpacing * MAGNIFICATION;
            }
            this._canvasWidth = res.shapeType == 1 ? 750 : 1060;
            this._canvasHeight = res.shapeType == 1 ? 1334 : 750;
            bgImgUrl = res.customizeImage;
            customizeControl = res.customizeControl || [];
          } else if (res.certificateType == 1) {
            bgImgUrl = res.image;
            title = res.title;
            redirectTo = res.redirectTo;
            customizeQrCode = res.customizeQrCode.img;
            qrCodeText = res.qrCodeText || '长按识别二维码';
            createdAt = `发证日期：${res.createdAt}`;
            enableAvatarShow = res.enableAvatarShow;
            nameTypeShow = res.nameTypeShow;
            longContent = res.longContent;
            enableShowQrCode = res.enableShowQrCode;
            enableInstitution = res.enableInstitution; //是否展示发证机构：1=展示；0=隐藏
            institutionName = res.institutionName; //机构名称
            enableGrantTime = res.enableGrantTime; //是否展示发证时间  1=展示；0=隐藏
            enableNumber = res.enableNumber; //是否展示证书编号 1=展示；0=隐藏
            enableStamp = res.enableStamp; //是否展示章戳  1=展示；2=自定义; 0=隐藏
            stampImg = res.enableStamp == 2 ? res.stampImg : res.backdropId == 3 ? require('@/assets/i/wap/camp/pass2.png') : require('@/assets/i/wap/camp/pass.png'); //章戳自定义图片
            this._canvasWidth = res.shapeType == 1 ? 750 : 1060;
            this._canvasHeight = res.shapeType == 1 ? 1334 : 750;
          }
          this._certInfo = res;
          this._cardInfo = {
            bgImgUrl,
            title,
            customizeControl,
            headimgurl,
            nickname,
            realName,
            number,
            qrCodeUrl,
            homeQrcode,
            customizeQrCode,
            redirectTo,
            qrCodeText,
            createdAt,
            enableAvatarShow,
            nameTypeShow,
            longContent,
            enableShowQrCode,
            enableInstitution,
            institutionName,
            enableGrantTime,
            enableNumber,
            enableStamp,
            stampImg
          };
          console.timeEnd('getCertofocateInfoTime');
          console.time('json2imageTime')
          this.resetCanvasSize();
          this.getCardImg();
        },
        failRes => {
          this.$loading.hide();
        }
      );
    },
    initJson2image() {
      this._json2image = new Json2canvas({
        width: 750,
        height: 1334
      });
    },
    resetCanvasSize() {
      if (this._json2image) {
        this._json2image.resetCanvasSize(this._canvasWidth, this._canvasHeight);
      }
    },
    destroyJson2image() {
      if (this._json2image) {
        this._json2image.destroy();
      }
    },
    async getCardImg() {
      if (!this._json2image) {
        return;
      }
      let data = [];

      let res = '';
      console.time('loadImgTime');
      try {
        await this._json2image.init();
        if (this._certInfo.certificateType == 2) {
          data = getCustCertJson(this._cardInfo, this._json2image);
        } else if (this._certInfo.certificateType == 1 && this._certInfo.shapeType == 1) {
          data = getVerCertJson(this._cardInfo, this._json2image);
        } else if (this._certInfo.certificateType == 1 && this._certInfo.shapeType == 2) {
          data = getHorCertJson(this._cardInfo, this._json2image);
        }
        console.log('data', data);
        await this._json2image.initJson(data);
        console.timeEnd('loadImgTime');
        console.time('drawTime');
        await this._json2image.startDraw();
        console.timeEnd('drawTime');
        console.time('toDataUrlTime');
        res = await this._json2image.toDataUrl('image/jpeg', 0.8);
        console.timeEnd('toDataUrlTime');
      } catch (error) {
        console.log('err', error);
        this.$loading.hide();
      }
      if (!res) {
        this.$loading.hide();
        return;
      }
      this.isShow = true;
      let ig = document.getElementById('honorCertImg');
      ig.setAttribute('src', res);
      this.$loading.hide();
      console.timeEnd('json2imageTime');
      console.timeEnd('totalTime');
      this.$emit('drawImageSuccess', {src:res, dir:this.direction})
      let blob = this._json2image.dataURItoBlob(res);
      console.log('图片大小KB', blob.size / 1024)
      if (this._isReceivedStudy == 0) {
        this.receiveCard(blob);
      } else if (this._isReceivedStudy == 1) {
        this.updateCardImage(blob);
      }
    },
    /**
     * 领取证书后上传最新的证书
     */
    receiveCard(blob) {
      utilJs.postMethod(
        global.apiurl + 'Certificate/receiveCard',
        {
          id: this._prodId,
          cardId: this._cardId,
          type: CERT_TYPE
        },
        res => {
          this._isReceivedStudy = 1;
          this.updateCardImage(blob);
        }
      );
    },
    /**
     * 上传证书到oss后保存到服务器
     */

    async updateCardImage(blob) {
      await this.getUploadImgSign();
      let blobDate = [];
      blob.name = this._prodId;
      blobDate.push(blob);
      utilJs.imgUpload(
        blobDate,
        this._imageSign,
        'course',
        res => {
          let image = res;
          utilJs.postMethod(`${global.apiurl}Certificate/updateCardImage`,
            {
              id: this._prodId,
              cardId: this._cardId,
              type: CERT_TYPE,
              image: image,
              shapeType: this._certInfo.shapeType
            },
            () => {
              this.$emit('updateImgeUrl', image);
            }
          );
        },
        fRes => {}
      );
    },
    goToAchievem() {
      this.$routerGo(this, 'push', {
        path: '/member/myAchievement/AchievementList'
      });
    }
  }
};
</script>

<style scoped>
.sec-popup /deep/ {
  background-color: transparent;
}
</style>
